package com.ruoyi.project.system.controller;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysPostService;
import com.ruoyi.project.system.service.ISysRoleService;
import com.ruoyi.project.system.service.ISysUserService;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    /**
     * 分页查询获取用户信息
     * @param user  可以根据信息进行模糊查询，
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 查询所有用户
     * @return
     */
    @GetMapping("/getAllUser")
    public AjaxResult getAllUser(){
        List<SysUser>  list=userService.getAllUser();
        return  AjaxResult.success(list);
    }



    /**
     * 查询所有用户（级别）
     * @return
     */
    @GetMapping("/getUserGrade")
    public AjaxResult getUsersGrade(){
        List<SysUser>  list=userService.getUsersGrade();
        return  AjaxResult.success(list);
    }
    /**
     * 查询所有用户（背景）
     * @return
     */
    @GetMapping("/getUserback")
    public AjaxResult getUsersback(){
        List<SysUser>  list=userService.getUsersback();
        return  AjaxResult.success(list);
    }



    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        System.out.println(user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getSuName())))
        {
            return AjaxResult.error("新增用户'" + user.getSuName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getSuPhone())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getSuName() + "'失败，手机号码已存在");
        }

        user.setCreateBy(SecurityUtils.getUsername());
        user.setSuPassword("123456");
        user.setCreateTime(new Date());
        user.setSuPassword(SecurityUtils.encryptPassword(user.getSuPassword()));
        return toAjax(userService.insertUser(user));
    }


    /**
     * 根据用户ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/getUserById/{suId}" })
    public AjaxResult getInfo(@PathVariable(value = "suId", required = false) Integer suId)
    {
//        AjaxResult ajax = AjaxResult.success();
//        List<SysRole> roles = roleService.selectRoleAll();
//        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
//        ajax.put("posts", postService.selectPostAll());
//        if (StringUtils.isNotNull(suId))
//        {
//            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(suId));
//            ajax.put("postIds", postService.selectPostListByUserId(suId));
//            ajax.put("roleIds", roleService.selectRoleListByUserId(suId));
//        }
        System.out.println(suId);
        SysUser sysUser = userService.selectUserById(suId);
        return AjaxResult.success(sysUser);
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getSuPhone())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getSuName() + "'失败，手机号码已存在");
        }

        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(new Date());

        return toAjax(userService.updateUser(user));
    }


    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{suIds}")
    public AjaxResult remove(@PathVariable Integer[] suIds)
    {
        return toAjax(userService.deleteUserByIds(suIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/restPwd/{suId}")
    public AjaxResult resetPwd(@PathVariable Integer suId)
    {
        String suPassword=SecurityUtils.encryptPassword("123456");
//        String UpdateBy=SecurityUtils.getUsername();
        return toAjax(userService.resetPwd(suId,suPassword));
    }


    /**
     * 给用户添加分配角色
     * @param ids  用户id数组
     * @param rids 角色id数组
     * @return
     */
    @PreAuthorize("@ss.hasPermi(' system:user:addRole')")
    @PostMapping("/addRole/{ids}/{rids}")
    public AjaxResult addRole(@PathVariable Integer[] ids ,@PathVariable Integer[] rids){
        int row = 0;
        try {
            row = userService.addRole(ids,rids);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(row);
    }























    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }




    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }
}